package gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Frame;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import net.miginfocom.swing.MigLayout;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.ListSelectionModel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import controller.CustomerCtr;
import controller.LocationCtr;
import controller.ProductCtr;
import controller.SupplierCtr;
import model.Customer;
import model.Order;
import model.Product;
import model.ProductLine;
import model.Supplier;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.Dimension;
import java.awt.Font;

public class Main extends JFrame {

	private JPanel contentPane;
	private JTextField order_customerNameField;
	private JTextField order_addressField;
	private JTextField order_phoneNumberField;
	private JTextField order_orderIdField;
	private JLabel lblPrice;
	private JTextField stock_productNameField;
	private JTextField customer_nameField;
	private JTextField customer_phoneNumberField;
	private JTextField customer_addressField;
	private JTextField customer_zipcodeField;
	private JTable customer_tableInfo;

	final JComboBox<?> supplier_productField;
	final JComboBox<?> order_productField;
	Order order = new Order();

	private CustomerCtr customerCtr = new CustomerCtr();
	private SupplierCtr supplierCtr = new SupplierCtr();
	private LocationCtr locationCtr = new LocationCtr();
	private ProductCtr productCtr = new ProductCtr();
	private JTextField customer_cityField;
	private JTextField customer_countryField;
	private JTable stock_informationTable;
	private JTextField stock_changingLabel1Field;
	private JTextField stock_changingLabel2Field;
	private JTextField supplier_nameField;
	private JTextField supplier_phoneNumberField;
	private JTextField supplier_addressField;
	private JTextField supplier_emailField;
	private JTextField supplier_zipcodeField;
	private JTextField supplier_descriptionField;
	private JTable supplier_informationTable;
	private JTextField supplier_cityField;
	private JTextField supplier_countryField;
	private JTextField stock_descriptionField;
	private JTextField stock_countryOfOriginField;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Main frame = new Main();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	@SuppressWarnings("serial")
	public Main() {
		setExtendedState(Frame.MAXIMIZED_BOTH);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 736, 434);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		contentPane.add(tabbedPane, BorderLayout.CENTER);

		JPanel panel = new JPanel();
		tabbedPane.addTab("Order", null, panel, null);
		panel.setLayout(new MigLayout("", "[][grow][]", "[][][][][][][][grow]"));

		JLabel lblCustomerName = new JLabel("Customer Name:");
		panel.add(lblCustomerName, "cell 0 0,alignx trailing");

		order_customerNameField = new JTextField();
		panel.add(order_customerNameField, "cell 1 0,growx");
		order_customerNameField.setColumns(10);
		order_customerNameField.getDocument().addDocumentListener(new DocumentListener() {

			@Override
			public void changedUpdate(DocumentEvent arg0) {
				order_addressField.setEnabled(true);
				order_phoneNumberField.setEnabled(true);
				
			}

			@Override
			public void insertUpdate(DocumentEvent arg0) {
				order_addressField.setEnabled(true);
				order_phoneNumberField.setEnabled(true);
				
			}

			@Override
			public void removeUpdate(DocumentEvent arg0) {
				order_addressField.setEnabled(true);
				order_phoneNumberField.setEnabled(true);
				
			}});


		JButton order_customerSearchButton = new JButton("Search");
		order_customerSearchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				try {
					String name = order_customerNameField.getText();
					String phoneNumber = order_phoneNumberField.getText();
					String address = order_addressField.getText();
					Customer customer = customerCtr.searchCustomer(name, phoneNumber, address, "", "");
					if(customer.getCustomerId() > 0)
					{
						order_addressField.setText(customer.getAddress());
						order_phoneNumberField.setText(customer.getPhoneNumber());
						
						order_addressField.setEnabled(false);
						order_phoneNumberField.setEnabled(false);
					}
					else
					{
						JOptionPane.showMessageDialog(null, "The number of Customers found was 0 or bigger than 1.");
					}
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		panel.add(order_customerSearchButton, "cell 2 0,grow");

		JLabel lblAddress = new JLabel("Address:");
		panel.add(lblAddress, "cell 0 1,alignx trailing");

		order_addressField = new JTextField();
		panel.add(order_addressField, "cell 1 1 2 1,growx");
		order_addressField.setColumns(10);

		JLabel lblNewLabel = new JLabel("Phone number:");
		panel.add(lblNewLabel, "cell 0 2,alignx trailing");

		order_phoneNumberField = new JTextField();
		panel.add(order_phoneNumberField, "cell 1 2 2 1,growx");
		order_phoneNumberField.setColumns(10);

		JLabel lblNewLabel_1 = new JLabel("Product:");
		panel.add(lblNewLabel_1, "cell 0 3,alignx trailing");

		JScrollPane scrollPane = new JScrollPane();
		scrollPane
		.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		panel.add(scrollPane, "cell 0 7 3 1,grow");
		final JTextPane order_informationField = new JTextPane();
		order_informationField.setFont(new Font("Courier New", Font.PLAIN, 11));
		order_informationField.setEditable(false);
		scrollPane.setViewportView(order_informationField);

		order_productField = new JComboBox<Object>();
		panel.add(order_productField, "cell 1 3,grow");

		JLabel lblNr = new JLabel("Nr:");
		panel.add(lblNr, "flowx,cell 2 3");

		JButton order_clearButton = new JButton("Clear");
		panel.add(order_clearButton, "cell 0 4,growx");

		final JSpinner order_productNrField = new JSpinner();
		order_productNrField.setModel(new SpinnerNumberModel(new Integer(1), new Integer(1), null, new Integer(1)));
		panel.add(order_productNrField, "cell 2 3,grow");

		
		final JButton order_addButton = new JButton("Add");
		order_addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					ProductLine productLine = new ProductLine(productCtr.searchProduct((String)order_productField.getSelectedItem()).getName(),(int)order_productNrField.getValue());
					if(productLine.getProduct().getCurrentStock() >= productLine.getQuantity())
					{
						order.insertProduct(productLine);
						order_informationField.setText(
								order_informationField.getText() + "\n \n" +
										productLine.getQuantity() + "  ITEMS OF || " + productLine.getProduct().getName() + "|| subtotal: " + productLine.getSubTotalPrice()
						);
						productLine.getProduct().setCurrentStock(productLine.getProduct().getCurrentStock() - productLine.getQuantity());
						productCtr.updateStock(productLine.getProduct().getProductId(), productLine.getProduct().getCurrentStock());
					}
					else
					{
						JOptionPane.showMessageDialog(null,"Not enough products in the stock, there are: " + productLine.getProduct().getCurrentStock() + " x " + productLine.getProduct().getName() + "  left.");
					}
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		});
		panel.add(order_addButton, "flowx,cell 1 4");

		final JButton order_removeButton = new JButton("Remove");
		panel.add(order_removeButton, "cell 1 4");

		JLabel lblNewLabel_2 = new JLabel("Date:");
		lblNewLabel_2.setVisible(false);
		panel.add(lblNewLabel_2, "cell 0 5,alignx trailing");

		JLabel lblFrom = new JLabel("From:");
		lblFrom.setVisible(false);
		panel.add(lblFrom, "flowx,cell 1 5");

		JComboBox<String> order_dateFromDay = new JComboBox<String>();
		order_dateFromDay.setVisible(false);
		DefaultComboBoxModel<String> dayArray = new DefaultComboBoxModel<String>();
		for (int i = 1; i <= 31; i++) {
			dayArray.addElement("" + i);
		}
		order_dateFromDay.setModel(dayArray);
		order_dateFromDay.setSelectedIndex(Calendar.getInstance().get(
				Calendar.DAY_OF_MONTH) - 1);
		panel.add(order_dateFromDay, "cell 1 5");

		JComboBox<String> order_dateFromMonth = new JComboBox<String>();
		order_dateFromMonth.setVisible(false);
		DefaultComboBoxModel<String> monthArray = new DefaultComboBoxModel<String>();
		for (int i = 1; i <= 12; i++) {
			monthArray.addElement("" + i);
		}
		order_dateFromMonth.setModel(monthArray);
		order_dateFromMonth.setSelectedIndex(Calendar.getInstance().get(
				Calendar.MONTH));
		panel.add(order_dateFromMonth, "cell 1 5");

		JComboBox<String> order_dateFromYear = new JComboBox<String>();
		order_dateFromYear.setVisible(false);

		DefaultComboBoxModel<String> yearArray = new DefaultComboBoxModel<String>();
		for (int i = Calendar.getInstance().get(Calendar.YEAR); i < 3000; i++) {
			yearArray.addElement("" + i);
		}
		order_dateFromYear.setModel(yearArray);
		panel.add(order_dateFromYear, "cell 1 5");

		JLabel lblTo = new JLabel("To:");
		lblTo.setVisible(false);
		panel.add(lblTo, "cell 1 5");

		order_orderIdField = new JTextField();
		order_orderIdField.setText("Order ID");
		panel.add(order_orderIdField, "cell 0 6,growx");
		order_orderIdField.setColumns(10);

		JButton order_orderSearchButton = new JButton("Search");
		panel.add(order_orderSearchButton, "flowx,cell 1 6");

		JButton order_finishOrderButton = new JButton("Finish order");
		order_finishOrderButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String customerName = order_customerNameField.getText().equals("") ? "UNREGISTERED" : order_customerNameField.getText();
				try {
					order.calculatePrice();
					order_informationField.setText(
							order_informationField.getText() + "\n\n\n" +
									"CUSTOMER: " + customerName + "  TOTAL PRICE : " + order.getPrice() + "\n" +
									"#####################################################################################"
					);
					order = new Order();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		panel.add(order_finishOrderButton, "cell 1 6");

		JComboBox<String> order_dateToDay = new JComboBox<String>();
		order_dateToDay.setVisible(false);
		DefaultComboBoxModel<String> toDayArray = new DefaultComboBoxModel<String>();
		for (int i = 1; i <= 31; i++) {
			toDayArray.addElement("" + i);
		}
		order_dateToDay.setModel(toDayArray);
		order_dateToDay.setSelectedIndex(Calendar.getInstance().get(
				Calendar.DAY_OF_MONTH));
		panel.add(order_dateToDay, "cell 1 5");

		JComboBox<String> order_dateToMonth = new JComboBox<String>();
		order_dateToMonth.setVisible(false);
		DefaultComboBoxModel<String> toMonthArray = new DefaultComboBoxModel<String>();
		for (int i = 1; i <= 12; i++) {
			toMonthArray.addElement("" + i);
		}
		order_dateToMonth.setModel(toMonthArray);
		order_dateToMonth.setSelectedIndex(Calendar.getInstance().get(
				Calendar.MONTH));
		panel.add(order_dateToMonth, "cell 1 5");

		JComboBox<String> order_dateToYear;
		order_dateToYear = new JComboBox<String>();
		order_dateToYear.setVisible(false);

		DefaultComboBoxModel<String> toYearArray = new DefaultComboBoxModel<String>();
		for (int i = Calendar.getInstance().get(Calendar.YEAR); i < 3000; i++) {
			toYearArray.addElement("" + i);
		}
		order_dateToYear.setModel(toYearArray);
		panel.add(order_dateToYear, "cell 1 5");

		

		

		

		final JPanel panel_2 = new JPanel();
		panel_2.addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent arg0) {

				customer_nameField.requestFocus();
			}
		});

		JPanel panel_1 = new JPanel();
		tabbedPane.addTab("Stock", null, panel_1, null);
		panel_1.setLayout(new MigLayout("", "[][grow]", "[][][][][][][][][grow]"));

		JLabel lblProductName = new JLabel("Product Name:");
		panel_1.add(lblProductName, "cell 0 0,alignx trailing");

		stock_productNameField = new JTextField();
		panel_1.add(stock_productNameField, "flowx,cell 1 0,growx");
		stock_productNameField.setColumns(10);
		
		JLabel lblNewLabel_5 = new JLabel("Description:");
		panel_1.add(lblNewLabel_5, "cell 0 1,alignx trailing");
		
		stock_descriptionField = new JTextField();
		stock_descriptionField.setMinimumSize(new Dimension(20, 22));
		panel_1.add(stock_descriptionField, "flowx,cell 1 1,aligny top");
		stock_descriptionField.setColumns(25);



		stock_changingLabel1Field = new JTextField();
		panel_1.add(stock_changingLabel1Field, "cell 1 2,growx");
		stock_changingLabel1Field.setColumns(10);

		stock_changingLabel2Field = new JTextField();
		panel_1.add(stock_changingLabel2Field, "cell 1 3,growx");
		stock_changingLabel2Field.setColumns(10);

		lblPrice = new JLabel("Purchase Price:");
		panel_1.add(lblPrice, "cell 0 4,alignx trailing");

		JLabel lblType = new JLabel("Type:");
		panel_1.add(lblType, "cell 1 0");

		final JLabel stock_changingLabel1 = new JLabel("Size:");
		panel_1.add(stock_changingLabel1, "cell 0 2,alignx trailing");

		final JLabel stock_changingLabel2 = new JLabel("Colour:");
		panel_1.add(stock_changingLabel2, "cell 0 3,alignx trailing");

		JComboBox stock_productTypeField = new JComboBox();
		stock_productTypeField.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent arg0) {
				String selected = arg0.getItem().toString();
				if(selected.equals("Clothing"))
				{
					stock_changingLabel1.setText("Size:");
					stock_changingLabel2.setText("Color:");

				}
				if(selected.equals("Equipment"))
				{
					stock_changingLabel1.setText("Type:");
					stock_changingLabel2.setText("Description:");

				}
				if(selected.equals("Gun Replicas"))
				{
					stock_changingLabel1.setText("Fabric:");
					stock_changingLabel2.setText("Caliber:");

				}
			}
		});
		stock_productTypeField.setModel(new DefaultComboBoxModel(new String[] {"Clothing", "Equipment", "Gun Replicas"}));
		panel_1.add(stock_productTypeField, "cell 1 0");

		final JSpinner stock_purchasePriceField = new JSpinner();
		stock_purchasePriceField.setMinimumSize(new Dimension(70, 20));
		stock_purchasePriceField.setModel(new SpinnerNumberModel(new Double(0), new Double(0), null, new Double(1)));
		panel_1.add(stock_purchasePriceField, "flowx,cell 1 4");

		JLabel lblSalesPrice = new JLabel("Sales Price:");
		panel_1.add(lblSalesPrice, "cell 0 5,alignx trailing");

		final JSpinner stock_salesPriceField = new JSpinner();
		stock_salesPriceField.setModel(new SpinnerNumberModel(new Double(0), null, null, new Double(1)));
		stock_salesPriceField.setMinimumSize(new Dimension(70, 20));
		panel_1.add(stock_salesPriceField, "flowx,cell 1 5");

		JLabel lblMinStock = new JLabel("Min. Stock:");
		panel_1.add(lblMinStock, "cell 0 6,alignx trailing");

		final JSpinner stock_minStockField = new JSpinner();
		stock_minStockField.setModel(new SpinnerNumberModel(new Integer(0), new Integer(0), null, new Integer(1)));
		stock_minStockField.setMinimumSize(new Dimension(70, 20));
		panel_1.add(stock_minStockField, "cell 1 6");

		JButton stock_clearButton = new JButton("Clear");
		panel_1.add(stock_clearButton, "cell 0 7,alignx right");

		JButton stock_searchButton = new JButton("Search");
		stock_searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					ArrayList<Product> productList = new ArrayList<Product>();
					if(productCtr.searchProduct(stock_productNameField.getText()).getProductId() > 0)
					{
						productList.add(productCtr.searchProduct(stock_productNameField.getText()));

						editStockTableData(productList);
					}
					else
					{
						JOptionPane.showMessageDialog(null, "No products found with that name");
						editStockTableData(productCtr.getAllProducts());
					}
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		});
		panel_1.add(stock_searchButton, "flowx,cell 1 7");

		JButton stock_showAllButton = new JButton("Show All");
		stock_showAllButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				try {
					editStockTableData(productCtr.getAllProducts());
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		panel_1.add(stock_showAllButton, "cell 1 7");

		JScrollPane scrollPane_2 = new JScrollPane();
		panel_1.add(scrollPane_2, "cell 0 8 2 1,grow");

		JLabel lblNumber = new JLabel("Number:");
		panel_1.add(lblNumber, "cell 1 0,alignx trailing");
		
		JLabel lblNewLabel_6 = new JLabel("Country of Origin:");
		panel_1.add(lblNewLabel_6, "cell 1 1");

		stock_countryOfOriginField = new JTextField();
		panel_1.add(stock_countryOfOriginField, "cell 1 1,alignx right");
		stock_countryOfOriginField.setColumns(25);
		
		final JSpinner stock_productNrField = new JSpinner();
		stock_productNrField.setMinimumSize(new Dimension(49, 20));
		stock_productNrField.setModel(new SpinnerNumberModel(new Integer(0), new Integer(0), null, new Integer(1)));
		panel_1.add(stock_productNrField, "cell 1 0");

		JButton stock_addButton = new JButton("Add");
		stock_addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String name = stock_productNameField.getText();
				String description = stock_descriptionField.getText();
				double purchasePrice = (double)stock_purchasePriceField.getValue();
				double salesPrice = (double)stock_salesPriceField.getValue();
				String countryOfOrigin = stock_countryOfOriginField.getText();
				int minStock = (int)stock_minStockField.getValue();
				int currentStock = 0;
				try {
					currentStock = productCtr.searchProduct(name).getProductId() < 0 ? (int)stock_productNrField.getValue() : productCtr.searchProduct(name).getCurrentStock() + (int)stock_productNrField.getValue();
				} catch (Exception e1) {
					e1.printStackTrace();
				} 
				
				productCtr.insertProduct(name, description, purchasePrice, salesPrice, countryOfOrigin, minStock, currentStock);
				refreshProducts();
			}
		});
		panel_1.add(stock_addButton, "cell 1 0");

		JButton stock_removeButton = new JButton("Remove");
		stock_removeButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					if(productCtr.searchProduct(stock_productNameField.getText()).getProductId() > 0)
					{
						if(JOptionPane.showConfirmDialog(null, "<html>Are you sure you want to delete <b>" + stock_productNameField.getText() + "</b> ?","Confirm",  JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
						{
							productCtr.removeProduct(stock_productNameField.getText());
							refreshProducts();
						}
					}
					else
					{
						JOptionPane.showMessageDialog(null, "No product with that name found!");
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});
		panel_1.add(stock_removeButton, "cell 1 0");

		

		stock_informationTable = new JTable();
		ArrayList<Product> productList;
		try {
			productList = productCtr.getAllProducts();
			editStockTableData(productList);
		} catch (Exception e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		
		scrollPane_2.setViewportView(stock_informationTable);

		JLabel label = new JLabel("");
		panel_1.add(label, "cell 1 5");
		
		
		tabbedPane.addTab("Customer", null, panel_2, null);
		panel_2.setLayout(new MigLayout("", "[][grow]", "[][][][][][][][grow]"));

		JLabel lblNewLabel_3 = new JLabel("Name:");
		panel_2.add(lblNewLabel_3, "cell 0 0,alignx trailing");

		final JButton customer_searchButton = new JButton("Search");
		customer_searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					ArrayList<Customer> customerList = customerCtr.searchCustomerList(
							customer_nameField.getText(), 
							customer_phoneNumberField.getText(), 
							customer_addressField.getText(), 
							customer_countryField.getText(), 
							customer_cityField.getText()
							);
					editCustomerTableData(customerList);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		customer_nameField = new JTextField();
		customer_nameField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_ENTER)
				{
					customer_searchButton.doClick();
				}

			}
		});
		panel_2.add(customer_nameField, "flowx,cell 1 0,growx");
		customer_nameField.setColumns(10);

		JLabel lblId = new JLabel("Phone Number:");
		panel_2.add(lblId, "cell 0 1,alignx trailing");

		customer_phoneNumberField = new JTextField();
		customer_phoneNumberField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_ENTER)
				{
					customer_searchButton.doClick();
				}

			}
		});
		panel_2.add(customer_phoneNumberField, "cell 1 1,growx");
		customer_phoneNumberField.setColumns(10);

		JLabel lblAddress_1 = new JLabel("Address:");
		panel_2.add(lblAddress_1, "cell 0 2,alignx trailing");

		customer_addressField = new JTextField();
		customer_addressField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_ENTER)
				{
					customer_searchButton.doClick();
				}
			}
		});
		panel_2.add(customer_addressField, "cell 1 2,growx");
		customer_addressField.setColumns(10);

		JLabel lblPhoneNumber = new JLabel("Zipcode:");
		panel_2.add(lblPhoneNumber, "cell 0 3,alignx trailing");

		customer_zipcodeField = new JTextField();
		customer_zipcodeField.getDocument().addDocumentListener(new DocumentListener() {

			@Override
			public void changedUpdate(DocumentEvent arg0) {

				try {
					if(isNumeric(customer_zipcodeField.getText()) && !customer_zipcodeField.getText().equals(""))
					{
						String city = locationCtr.getCity(Integer.parseInt(customer_zipcodeField.getText()));
						String country = locationCtr.getCountry(Integer.parseInt(customer_zipcodeField.getText()));
						if(!city.equals("") && !country.equals(""))
						{
							customer_cityField.setText(city);
							customer_countryField.setText(country);
							customer_cityField.setEnabled(false);
							customer_countryField.setEnabled(false);
						}
						else
						{
							customer_cityField.setEnabled(true);
							customer_countryField.setEnabled(true);
						}
					}
				} catch (NumberFormatException e1) {

					e1.printStackTrace();
				} catch (Exception e1) {

					e1.printStackTrace();
				}
			}

			@Override
			public void insertUpdate(DocumentEvent arg0) {

				try {
					if(isNumeric(customer_zipcodeField.getText()) && !customer_zipcodeField.getText().equals(""))
					{
						String city = locationCtr.getCity(Integer.parseInt(customer_zipcodeField.getText()));
						String country = locationCtr.getCountry(Integer.parseInt(customer_zipcodeField.getText()));
						if(!city.equals("") && !country.equals(""))
						{
							customer_cityField.setText(city);
							customer_countryField.setText(country);
							customer_cityField.setEnabled(false);
							customer_countryField.setEnabled(false);
						}
						else
						{
							customer_cityField.setEnabled(true);
							customer_countryField.setEnabled(true);
						}
					}
				} catch (NumberFormatException e1) {

					e1.printStackTrace();
				} catch (Exception e1) {

					e1.printStackTrace();
				}
			}

			@Override
			public void removeUpdate(DocumentEvent arg0) {

				try {
					if(isNumeric(customer_zipcodeField.getText()) && !customer_zipcodeField.getText().equals(""))
					{
						String city = locationCtr.getCity(Integer.parseInt(customer_zipcodeField.getText()));
						String country = locationCtr.getCountry(Integer.parseInt(customer_zipcodeField.getText()));
						if(!city.equals("") && !country.equals(""))
						{
							customer_cityField.setText(city);
							customer_countryField.setText(country);
							customer_cityField.setEnabled(false);
							customer_countryField.setEnabled(false);
						}
						else
						{
							customer_cityField.setEnabled(true);
							customer_countryField.setEnabled(true);
						}
					}
				} catch (NumberFormatException e1) {

					e1.printStackTrace();
				} catch (Exception e1) {

					e1.printStackTrace();
				}
			}});

		panel_2.add(customer_zipcodeField, "cell 1 3,growx");
		customer_zipcodeField.setColumns(10);

		JButton customer_addCustomerButton = new JButton("Add Customer");
		customer_addCustomerButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					String name = customer_nameField.getText();
					String phoneNumber = customer_phoneNumberField.getText();
					String address = customer_addressField.getText();
					String country = customer_countryField.getText();
					int zipcode = customer_zipcodeField.getText().equals("") ? -1 : Integer.parseInt(customer_zipcodeField.getText());
					String city = customer_cityField.getText();
					int isCompany = 1;// Integer.parseInt(customer_isCompanyField.getText());

					if(!name.equals("") && !phoneNumber.equals("") && ! address.equals("") && zipcode != -1)
					{
						if(customerCtr.searchCustomerList("", phoneNumber, "", "", "").size() == 0)
						{
							customerCtr.insertCustomer(name, phoneNumber, address, country, city, zipcode, isCompany);
							if(locationCtr.getCity(zipcode).equals(""))
							{
								locationCtr.insertLocation(zipcode, city, country);
							}
						}
						else
						{
							JOptionPane.showMessageDialog(panel_2.getParent(), "This Phone Number is already in the database.");
						}
					}
					else
					{
						JOptionPane.showMessageDialog(panel_2.getParent(), "Empty fields are not allowed!");
					}
				} catch (Exception e) {

					e.printStackTrace();
				}
			}
		});
		customer_addCustomerButton.setFocusable(false);
		panel_2.add(customer_addCustomerButton, "cell 1 0");

		JLabel lblCity = new JLabel("City:");
		panel_2.add(lblCity, "cell 0 4,alignx trailing");

		customer_cityField = new JTextField();
		customer_cityField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_ENTER)
				{
					customer_searchButton.doClick();
				}
			}
		});
		panel_2.add(customer_cityField, "cell 1 4,growx");
		customer_cityField.setColumns(10);

		JLabel lblCountry = new JLabel("Country:");
		panel_2.add(lblCountry, "cell 0 5,alignx trailing");

		customer_countryField = new JTextField();
		customer_countryField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_ENTER)
				{
					customer_searchButton.doClick();
				}
			}
		});
		panel_2.add(customer_countryField, "cell 1 5,growx");
		customer_countryField.setColumns(10);



		JButton customer_clearButton = new JButton("Clear");
		customer_clearButton.setFocusable(false);
		customer_clearButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				customer_addressField.setText("");
				customer_cityField.setText("");
				customer_cityField.setEnabled(true);
				customer_countryField.setText("");
				customer_countryField.setEnabled(true);
				customer_nameField.setText("");
				customer_phoneNumberField.setText("");
				customer_zipcodeField.setText("");

			}
		});
		panel_2.add(customer_clearButton, "cell 0 6,growx");
		panel_2.add(customer_searchButton, "flowx,cell 1 6");

		JButton customer_showAllButton = new JButton("Show All");
		customer_showAllButton.setFocusable(false);
		customer_showAllButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					ArrayList<Customer> customerList = customerCtr.getAllCustomers();
					editCustomerTableData(customerList);

				} catch (Exception e) {

					e.printStackTrace();
				}
			}
		});


		panel_2.add(customer_showAllButton, "cell 1 6");

		JScrollPane scrollPane_1 = new JScrollPane();
		panel_2.add(scrollPane_1, "cell 0 7 2 1,grow");

		customer_tableInfo = new JTable();
		scrollPane_1.setViewportView(customer_tableInfo);
		customer_tableInfo
		.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		JButton customer_removeCustomerButton = new JButton("Remove Customer");
		customer_removeCustomerButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String name = customer_nameField.getText();
				String phoneNumber = customer_phoneNumberField.getText();
				String address = customer_addressField.getText();
				String country = customer_countryField.getText();
				int isCompany = -1; //customer_isCompanyField.getText();
				int zipcode = customer_zipcodeField.getText().equals("") ? -1 : Integer.parseInt(customer_zipcodeField.getText());
				String city = customer_cityField.getText();
				try {
					if(customerCtr.searchCustomer(name, phoneNumber, address, country, city).getName() != null)
					{
						if(JOptionPane.showConfirmDialog(null, "<html>Are you sure you want to delete <b>" + customerCtr.searchCustomer(name, phoneNumber, address, country, city).getName() + "</b> ?","Confirm",  JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
						{
							customerCtr.removeCustomer(name, phoneNumber, address, country, city, zipcode, isCompany);
						}
					}
					else
					{
						JOptionPane.showMessageDialog(null, "Not enough information to search.");
					}
				} catch (Exception e) {

					e.printStackTrace();
				}
			}
		});
		panel_2.add(customer_removeCustomerButton, "cell 1 0");
		try {
			ArrayList<Customer> customerList = customerCtr.getAllCustomers();
			editCustomerTableData(customerList);

		} catch (Exception e) {

			e.printStackTrace();
		}

		JPanel panel_3 = new JPanel();
		tabbedPane.addTab("Supplier", null, panel_3, null);
		panel_3.setLayout(new MigLayout("", "[][grow]", "[][][][][][][][][][][grow]"));

		supplier_productField = new JComboBox();
		refreshProducts();


		panel_3.add(supplier_productField, "cell 1 8,growx");

		JLabel lblNewLabel_4 = new JLabel("Name:");
		panel_3.add(lblNewLabel_4, "cell 0 0,alignx trailing");

		supplier_nameField = new JTextField();
		panel_3.add(supplier_nameField, "flowx,cell 1 0,growx");
		supplier_nameField.setColumns(10);

		JLabel lblPhoneNumber_1 = new JLabel("Phone Number:");
		panel_3.add(lblPhoneNumber_1, "cell 0 1,alignx trailing");

		supplier_phoneNumberField = new JTextField();
		panel_3.add(supplier_phoneNumberField, "cell 1 1,growx");
		supplier_phoneNumberField.setColumns(10);

		JLabel lblAddress_2 = new JLabel("Address:");
		panel_3.add(lblAddress_2, "cell 0 2,alignx trailing");

		supplier_addressField = new JTextField();
		panel_3.add(supplier_addressField, "cell 1 2,growx");
		supplier_addressField.setColumns(10);

		JLabel lblEmail = new JLabel("Email:");
		panel_3.add(lblEmail, "cell 0 3,alignx trailing");

		supplier_emailField = new JTextField();
		panel_3.add(supplier_emailField, "cell 1 3,growx");
		supplier_emailField.setColumns(10);

		JLabel lblZipcode = new JLabel("Zipcode:");
		panel_3.add(lblZipcode, "cell 0 4,alignx trailing");

		supplier_zipcodeField = new JTextField();
		supplier_zipcodeField.getDocument().addDocumentListener(new DocumentListener() {

			@Override
			public void changedUpdate(DocumentEvent arg0) {

				try {
					if(isNumeric(supplier_zipcodeField.getText()) && !supplier_zipcodeField.getText().equals(""))
					{
						String city = locationCtr.getCity(Integer.parseInt(supplier_zipcodeField.getText()));
						String country = locationCtr.getCountry(Integer.parseInt(supplier_zipcodeField.getText()));
						if(!city.equals("") && !country.equals(""))
						{
							supplier_cityField.setText(city);
							supplier_countryField.setText(country);
							supplier_cityField.setEnabled(false);
							supplier_countryField.setEnabled(false);
						}
						else
						{
							supplier_cityField.setEnabled(true);
							supplier_countryField.setEnabled(true);
						}
					}
				} catch (NumberFormatException e1) {

					e1.printStackTrace();
				} catch (Exception e1) {

					e1.printStackTrace();
				}
			}

			@Override
			public void insertUpdate(DocumentEvent arg0) {

				try {
					if(isNumeric(supplier_zipcodeField.getText()) && !supplier_zipcodeField.getText().equals(""))
					{
						String city = locationCtr.getCity(Integer.parseInt(supplier_zipcodeField.getText()));
						String country = locationCtr.getCountry(Integer.parseInt(supplier_zipcodeField.getText()));
						if(!city.equals("") && !country.equals(""))
						{
							supplier_cityField.setText(city);
							supplier_countryField.setText(country);
							supplier_cityField.setEnabled(false);
							supplier_countryField.setEnabled(false);
						}
						else
						{
							supplier_cityField.setEnabled(true);
							supplier_countryField.setEnabled(true);
						}
					}
				} catch (NumberFormatException e1) {

					e1.printStackTrace();
				} catch (Exception e1) {

					e1.printStackTrace();
				}
			}

			@Override
			public void removeUpdate(DocumentEvent arg0) {

				try {
					if(isNumeric(supplier_zipcodeField.getText()) && !supplier_zipcodeField.getText().equals(""))
					{
						String city = locationCtr.getCity(Integer.parseInt(supplier_zipcodeField.getText()));
						String country = locationCtr.getCountry(Integer.parseInt(supplier_zipcodeField.getText()));
						if(!city.equals("") && !country.equals(""))
						{
							supplier_cityField.setText(city);
							supplier_countryField.setText(country);
							supplier_cityField.setEnabled(false);
							supplier_countryField.setEnabled(false);
						}
						else
						{
							supplier_cityField.setEnabled(true);
							supplier_countryField.setEnabled(true);
						}
					}
				} catch (NumberFormatException e1) {

					e1.printStackTrace();
				} catch (Exception e1) {

					e1.printStackTrace();
				}
			}});
		panel_3.add(supplier_zipcodeField, "cell 1 4,growx");
		supplier_zipcodeField.setColumns(10);

		JLabel lblCity_1 = new JLabel("City:");
		panel_3.add(lblCity_1, "cell 0 5,alignx trailing");

		supplier_cityField = new JTextField();
		panel_3.add(supplier_cityField, "cell 1 5,growx");
		supplier_cityField.setColumns(10);

		JLabel lblCountry_1 = new JLabel("Country:");
		panel_3.add(lblCountry_1, "cell 0 6,alignx trailing");

		supplier_countryField = new JTextField();
		panel_3.add(supplier_countryField, "cell 1 6,growx");
		supplier_countryField.setColumns(10);

		JLabel lblDescription = new JLabel("Description:");
		panel_3.add(lblDescription, "cell 0 7,alignx trailing");

		JButton supplier_addSupplierButton = new JButton("Add Supplier");
		supplier_addSupplierButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					String name = supplier_nameField.getText();
					String phoneNumber = supplier_phoneNumberField.getText();
					String email = supplier_emailField.getText();
					String address = supplier_addressField.getText();
					String country = supplier_countryField.getText();
					String description = supplier_descriptionField.getText();

					int productId = productCtr.searchProduct((String)supplier_productField.getSelectedItem()).getProductId();
					int zipcode = supplier_zipcodeField.getText().equals("") ? -1 : Integer.parseInt(supplier_zipcodeField.getText());
					String city = supplier_cityField.getText();


					if(!name.equals("") && !phoneNumber.equals("") && !address.equals("") && !email.equals("") && zipcode != -1 && !city.equals(""))
					{
						if(supplierCtr.searchSupplierList(name, phoneNumber, address, email, zipcode, country, city, productId).size() == 0)
						{
							supplierCtr.insertSupplier(name, phoneNumber, address, email, zipcode, description, productId);
							if(locationCtr.getCity(zipcode).equals(""))
							{
								locationCtr.insertLocation(zipcode, city, country);
							}
						}
						else
						{
							JOptionPane.showMessageDialog(panel_2.getParent(), "This Phone Number is already in the database.");
						}
					}
					else
					{
						JOptionPane.showMessageDialog(panel_2.getParent(), "Empty fields are not allowed!");
					}
				} catch (Exception e) {

					e.printStackTrace();
				}
			}
		});
		panel_3.add(supplier_addSupplierButton, "cell 1 0");

		supplier_descriptionField = new JTextField();
		panel_3.add(supplier_descriptionField, "cell 1 7,growx");
		supplier_descriptionField.setColumns(10);

		JLabel supplier_productLabel = new JLabel("Product:");
		panel_3.add(supplier_productLabel, "cell 0 8,alignx trailing");



		JButton supplier_clearButton = new JButton("Clear");
		supplier_clearButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				supplier_addressField.setText("");
				supplier_descriptionField.setText("");

				supplier_emailField.setText("");
				supplier_cityField.setText("");
				supplier_cityField.setEnabled(true);
				supplier_countryField.setText("");
				supplier_countryField.setEnabled(true);
				supplier_nameField.setText("");
				supplier_phoneNumberField.setText("");
				supplier_zipcodeField.setText("");
			}
		});
		panel_3.add(supplier_clearButton, "cell 0 9,growx");

		JButton supplier_searchButton = new JButton("Search");
		supplier_searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					int zipcode = supplier_zipcodeField.getText().equals("") ? -1 : Integer.parseInt(supplier_zipcodeField.getText());
					ArrayList<Supplier> supplierList = supplierCtr.searchSupplierList(
							supplier_nameField.getText(), 
							supplier_phoneNumberField.getText(), 
							supplier_addressField.getText(), 
							supplier_emailField.getText(), 
							zipcode, 
							supplier_countryField.getText(), 
							supplier_cityField.getText(), 
							-1 //productCtr.searchProduct((String)supplier_productField.getSelectedItem()).getProductId()
							);

					editSupplierTableData(supplierList);

				} catch (Exception a) {
					a.printStackTrace();
				}
			}
		});
		panel_3.add(supplier_searchButton, "flowx,cell 1 9");

		JScrollPane scrollPane_3 = new JScrollPane();
		panel_3.add(scrollPane_3, "cell 0 10 2 1,grow");

		supplier_informationTable = new JTable();
		scrollPane_3.setViewportView(supplier_informationTable);
		supplier_informationTable.setModel(new DefaultTableModel(
				new Object[][] {
				},
				new String[] {
						"ID", "Name", "Phone Number", "Email", "Description", "Address", "City", "Country", "Zipcode"
				}
				));

		JButton supplier_showAllButton = new JButton("Show All");
		supplier_showAllButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					ArrayList<Supplier> supplierList = supplierCtr.getAllSuppliers();
					editSupplierTableData(supplierList);

				} catch (Exception ee) {

					ee.printStackTrace();
				}
			}
		});
		panel_3.add(supplier_showAllButton, "cell 1 9");

		JButton btnRemoveSupplier = new JButton("Remove Supplier");
		btnRemoveSupplier.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					String name = supplier_nameField.getText();
					String phoneNumber = supplier_phoneNumberField.getText();
					String address = supplier_addressField.getText();
					String email = supplier_emailField.getText();
					String description = supplier_descriptionField.getText();
					String country = supplier_countryField.getText();
					String city = supplier_cityField.getText();
					int zipcode = supplier_zipcodeField.getText().equals("") ? -1 : Integer.parseInt(supplier_zipcodeField.getText());
					int productId = productCtr.searchProduct((String)supplier_productField.getSelectedItem()).getProductId();

					if(supplierCtr.searchSupplier(name, phoneNumber, address, email, zipcode, country, city, productId).getName() != null)
					{
						if(JOptionPane.showConfirmDialog(null, "<html>Are you sure you want to delete <b>" + supplierCtr.searchSupplier(name, phoneNumber, address, email, zipcode, country, city, productId).getName() + "</b> ?","Confirm",  JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
						{
							supplierCtr.removeSupplier(name, phoneNumber, address, country, city, email, zipcode, productId);
						}
					}
					else
					{
						JOptionPane.showMessageDialog(null, "Not enough information to search.");
					}
				} catch (Exception s) {

					s.printStackTrace();
				}
			}
		});
		panel_3.add(btnRemoveSupplier, "cell 1 0");



	}
	private void refreshProducts()
	{
		try {
			ArrayList<Product> productList = productCtr.getAllProducts();
			String[] objectList = new String[productList.size()];

			int i=0;
			for(Product product : productList)
			{
				objectList[i] = product.getName();
				i++;
			}
			supplier_productField.setModel(new DefaultComboBoxModel(objectList));
			order_productField.setModel(new DefaultComboBoxModel(objectList));
		} catch (Exception e2) {
			e2.printStackTrace();
		}
	}

	public static boolean isNumeric(String str) {
		NumberFormat formatter = NumberFormat.getInstance();
		ParsePosition pos = new ParsePosition(0);
		formatter.parse(str, pos);
		return str.length() == pos.getIndex();
	}
	protected void editStockTableData(ArrayList<Product> productList) {
		Object[][] objectList = new Object[productList.size()][9];
		int i = 0;
		for (Product product : productList) {
			objectList[i][0] = product.getProductId();
			objectList[i][1] = product.getName();
			objectList[i][2] = product.getDescription();
			objectList[i][3] = product.getPurchasePrice();
			objectList[i][4] = product.getSalesPrice();
			objectList[i][5] = product.getCountryOfOrigin();
			objectList[i][6] = product.getMinStock();
			objectList[i][7] = product.getCurrentStock();
			try {
				objectList[i][8] = supplierCtr.searchSupplier("", "", "", "", -1, "", "", product.getProductId()).getName();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			i++;
		}
		stock_informationTable.setModel(new DefaultTableModel(objectList,
				new String[] {
					"ID", "Name", "Description", "Purchase Price", "Sales Price", "Origin", "Min. Stock", "Current Stock", "Supplier"
				}
			) {
				boolean[] columnEditables = new boolean[] {
					false, false, false, false, false, false, true, true, false
				};
				public boolean isCellEditable(int row, int column) {
					return columnEditables[column];
				}
			});
			stock_informationTable.getColumnModel().getColumn(0).setPreferredWidth(29);
			stock_informationTable.getColumnModel().getColumn(1).setPreferredWidth(157);
			stock_informationTable.getColumnModel().getColumn(2).setPreferredWidth(244);
			stock_informationTable.getColumnModel().getColumn(3).setPreferredWidth(87);
			stock_informationTable.getColumnModel().getColumn(5).setPreferredWidth(139);
			stock_informationTable.getColumnModel().getColumn(8).setPreferredWidth(22);

	}
	protected void editSupplierTableData(ArrayList<Supplier> supplierList) {
		Object[][] objectList = new Object[supplierList.size()][9];
		int i = 0;
		for (Supplier supplier : supplierList) {
			objectList[i][0] = supplier.getSupplierId();
			objectList[i][1] = supplier.getName();
			objectList[i][2] = supplier.getPhoneNumber();
			objectList[i][3] = supplier.getEmail();
			objectList[i][4] = supplier.getDescription();
			objectList[i][5] = supplier.getAddress();
			objectList[i][6] = supplier.getCity();
			objectList[i][7] = supplier.getCountry();
			objectList[i][8] = supplier.getZipcode();
			i++;
		}
		supplier_informationTable
		.setModel(new DefaultTableModel(objectList, new String[] {
				"ID", "Name", "Phone Number", "Email", "Description",
				"Address", "City", "Country", "Zipcode" }));

	}

	protected void editCustomerTableData(ArrayList<Customer> customerList) {
		Object[][] objectList = new Object[customerList.size()][7];
		int i = 0;
		for (Customer customer : customerList) {
			objectList[i][0] = customer.getCustomerId();
			objectList[i][1] = customer.getName();
			objectList[i][2] = customer.getPhoneNumber();
			objectList[i][3] = customer.getAddress();
			objectList[i][4] = customer.getCountry();
			objectList[i][5] = customer.getCity();
			objectList[i][6] = customer.getZipcode();
			i++;
		}
		customer_tableInfo.setModel(new DefaultTableModel(objectList,
				new String[] { "ID", "Name", "Phone Number", "Address",
				"Country", "City", "Zipcode" }) {
			Class[] columnTypes = new Class[] { String.class, String.class,
					String.class, String.class, String.class, String.class,
					String.class };

			public Class<?> getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}
		});
		customer_tableInfo.getColumnModel().getColumn(0).setResizable(false);
		customer_tableInfo.getColumnModel().getColumn(0).setPreferredWidth(16);
		customer_tableInfo.getColumnModel().getColumn(1).setPreferredWidth(86);
		customer_tableInfo.getColumnModel().getColumn(3).setPreferredWidth(177);
		customer_tableInfo.getColumnModel().getColumn(4).setPreferredWidth(88);
		customer_tableInfo.getColumnModel().getColumn(5).setPreferredWidth(91);
		customer_tableInfo.getColumnModel().getColumn(6).setPreferredWidth(58);

	}

}
